#!/usr/bin/env node

const Koa = require('koa');
const app = new Koa(),
      bodyparser = require('koa-bodyparser'),
      tasks = require('./routes/tasks'),
      users = require('./routes/users'),
      json = require('koa-json'),
      logger = require('koa-logger'),
      jwt = require('koa-jwt'),
      jwt2 = require('jsonwebtoken'),
      { JWT_KEY } = require('./lib/constant'), 
      log = console.log;



app.use(json());
app.use(logger());
app.use(jwt({secret: JWT_KEY}).unless({path:/\/api\/users\/login$/}));
app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }));

app.use(async(ctx, next) => {  
  // get token
  let token = ctx.header.authorization;
  if(typeof token !== 'undefined'){
    token = token.split(' ')[1];
    // parse token get user id
    let user = jwt2.verify(token, JWT_KEY);
    ctx.userId = user.id;
  }
  
  await next();
})
app.use(tasks.routes());
app.use(users.routes());

app.listen(8080);

